package cheme.ProcessEditor;

import java.util.Iterator;

import org.eclipse.draw2d.EventListenerList;
import org.eclipse.gef.DefaultEditDomain;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.ui.IEditorPart;

public class ChemeEditDomain extends DefaultEditDomain
{
	public interface ChemeKeyListener
	{
		public void keyPressed(KeyEvent event);
		public void keyReleased(KeyEvent event);
	}
	
	private EventListenerList eventListeners = new EventListenerList();
	
	public void addKeyListener(ChemeKeyListener listener)
	{
		eventListeners.addListener(ChemeKeyListener.class, listener);
	}
	
	public void removeKeyListener(ChemeKeyListener listener)
	{
		eventListeners.removeListener(ChemeKeyListener.class, listener);
	}
	
	public ChemeEditDomain(IEditorPart editorPart)
	{
		super(editorPart);
	}

	@Override
	public void keyDown(KeyEvent keyEvent, EditPartViewer viewer)
	{
		notifyKeyPress(keyEvent);
		super.keyDown(keyEvent, viewer);
	}
	
	@Override
	public void keyTraversed(TraverseEvent traverseEvent, EditPartViewer viewer)
	{
		super.keyTraversed(traverseEvent, viewer);
	}
	
	@Override
	public void keyUp(KeyEvent keyEvent, EditPartViewer viewer)
	{
		notifyKeyRelease(keyEvent);
		super.keyUp(keyEvent, viewer);
	}
	
	private void notifyKeyPress(KeyEvent keyEvent)
	{

		Iterator iter = eventListeners.getListeners(ChemeKeyListener.class);
		
		while (iter.hasNext()) 
		{
			((ChemeKeyListener)iter.next()).keyPressed(keyEvent);
		}
	}
	
	private void notifyKeyRelease(KeyEvent keyEvent)
	{

		Iterator iter = eventListeners.getListeners(ChemeKeyListener.class);
		
		while (iter.hasNext()) 
		{
			((ChemeKeyListener)iter.next()).keyReleased(keyEvent);
		}
	}
}
